<template>
  <div class="app-container">
    <div class="head-container">
      <span slot="right">
        <div style="display: inline-block;margin: 0px 2px;">
          <el-upload
            ref="upload"
            v-permission="['admin','onduty:import']"
            :show-file-list="false"
            :before-upload="beforeupload"
            :on-success="handleSuccessFile"
            :on-error="handleErrorFile"
            :action="baseApi + '/api/onduty/upload'"
            :headers="headers"
            accept=".xls,.xlsx"
            enctype="multipart/form-data"
          >
            <el-button type="primary" class="filter-item" size="mini" icon="el-icon-upload">导入</el-button>
          </el-upload>
        </div>
        <el-button
          size="mini"
          class="filter-item"
          type="text"
          style="background:#fffffb;"
          @click="downloadModel"
        >
          <svg-icon icon-class="log" />
          下载模板</el-button>
      </span>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="日期" prop="date">
            <el-date-picker
              v-model="form.time"
              type="date"
              placeholder="选择日期"
              style="width: 370px;"
            />
            <!-- <el-date-picker v-model="form.date" type="datetime" style="width: 370px;" /> -->
          </el-form-item>
          <el-form-item label="名称">
            <el-input v-model="form.name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="内容">
            <el-input v-model="form.content" :rows="4" type="textarea" style="width: 370px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="time" label="日期" align="center" :formatter="formatter" />
        <el-table-column prop="content" label="内容" align="center" />
        <el-table-column prop="createTime" label="创建日期" align="center" />
        <el-table-column v-if="checkPer(['admin','onduty:edit','onduty:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { downloadFile } from '@/utils/index'
import { mapGetters } from 'vuex'
import { download } from '@/api/data'
import crudOnduty from '@/api/onduty'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'

const defaultForm = { id: null, time: null, name: null, content: null, createBy: null, updateBy: null, createTime: null, updateTime: null }
export default {
  name: 'Onduty',
  components: { pagination, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '事件表', url: 'api/onduty', idField: 'id', sort: 'time,desc', crudMethod: { ...crudOnduty },
      optShow: {
        add: true,
        edit: false,
        del: false,
        reset: false
      }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      permission: {
        add: ['admin', 'onduty:add'],
        edit: ['admin', 'onduty:edit'],
        del: ['admin', 'onduty:del']
      },
      rules: {
        id: [
          { required: true, message: 'id不能为空', trigger: 'blur' }
        ]
      }}
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToCU](form) {
      this.form.time = new Date()
    },
    beforeupload(file) {
      const isLt1M = file.size / 1024 / 1024 < 100
      if (!isLt1M) {
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.fileName = file.name
      return isLt1M
    },

    handleSuccessFile(res, file) {
      if (res.state === 'success') {
        this.$message({
          message: res.info,
          type: 'success'
        })
        this.crud.toQuery()
        this.crud.refresh()
      } else {
        this.$message.error(res.message)
      }
    },
    /** 失败状态 */
    handleErrorFile(file) {
      this.$message.error('数据导入失败！')
    },
    downloadModel() {
      var params = { }
      params.id = -1
      download(this.crud.url + '/export', params).then(result => {
        downloadFile(result, '日期', 'xlsx')
      })
    },
    formatter(row, column, cellValue, index) {
      let format = 'YYYY-mm-dd'
      const date = new Date(cellValue)
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString()
      }
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format)
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'))
        }
      })
      return format
    }
  }
}
</script>

<style scoped>

</style>
